<?php
/**
 * Created by PhpStorm.
 * User: DongYao
 * Date: 2017/12/17
 * Time: 上午11:55
 */

namespace App\Observers;

use App\Tables\User;
use App\Tables\UserAgentExtend;
use App\Tables\AgentRelation;
use DB;
use Log;

class AgentObserver
{
    public function created(UserAgentExtend $agent)
    {
        DB::transaction(function () use ($agent) {
            if ($agent->agent_level == 2) {
                $relation = new AgentRelation();
                $relation->parent_id = $agent->parent_user_id;
                $relation->child_id = $agent->user_id;
                $relation->save();
            } else if ($agent->agent_level == 3) {
                /**
                 * 添加与2级代理的关系
                 */
                $relation = new AgentRelation();
                $relation->parent_id = $agent->parent_user_id;
                $relation->child_id = $agent->user_id;
                $relation->save();

                /**
                 * 添加与1级代理的关系
                 */
                $up_level_user = UserAgentExtend::where('user_id', $agent->parent_user_id)->first(); // 获取上级代理信息

                $relation = new AgentRelation();
                $relation->parent_id = $up_level_user->parent_user_id; // 一级代理id
                $relation->child_id = $agent->user_id;
                $relation->save();
            }
        }, 5);
    }

    public function saved (UserAgentExtend $agentExtend)
    {
        /*if ($agentExtend->agent_level == 1) {
            $agents = User::agents()->ofChildren($agentExtend->user_id)->get();

            $agents->each(function ($item) use ($agentExtend) {
                $level_key = 'v' . $item->extension->agent_level;
                $item->extension->proration = $agentExtend->prorations[$level_key];
                $item->extension->prorations = $agentExtend->prorations;
                $item->extension->save();
                Log::debug('修改下级代理分红信息', [$item->name, $agentExtend->prorations]);
            });
        }*/

    }
}